package com.bj.disc.base

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.ai3d.rfid.R
import com.ai3d.rfid.databinding.ViewTopBarBinding
import com.ai3d.rfid.ext.utils.layoutInflater

/**
 * @ProjectName : Trias
 * @Author : weijinsong
 * @Time : 2022/9/3 11:41
 * @Description : 顶部导航通用TopBar
 */
class TopBar : ConstraintLayout {
    var viewBinding: ViewTopBarBinding =
        ViewTopBarBinding.inflate(context.layoutInflater!!, this, true)
    private val action: Action by lazy { Action() }
    var listener: (() -> Unit)? = null

    constructor(c: Context) : this(c, null)
    constructor(c: Context, attrs: AttributeSet?) : this(c, attrs, 0)
    constructor(c: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        c,
        attrs,
        defStyleAttr
    ) {
        initWithAttr(c, attrs)
    }

    private fun initWithAttr(context: Context, attrs: AttributeSet?) {
        viewBinding.action = action
        val typedArray: TypedArray =
            context.theme.obtainStyledAttributes(attrs, R.styleable.TopBar, 0, 0)
        val resId = typedArray.getResourceId(R.styleable.TopBar_iconRes, 0)
        val text = typedArray.getString(R.styleable.TopBar_text)
        var textColor = typedArray.getColor(
            R.styleable.TopBar_textColor,
            ContextCompat.getColor(App.instance, R.color.bg_assist_color)
        )
        val backVisible = typedArray.getInt(R.styleable.TopBar_backVisible, View.VISIBLE)
        val titleVisible = typedArray.getInt(R.styleable.TopBar_titleVisible, View.VISIBLE)
        typedArray.recycle()

        if (resId != 0) {
            viewBinding.ivBack.setImageResource(resId)
        }
        viewBinding.tvTitle.text = text
        viewBinding.ivBack.visibility = backVisible
        viewBinding.tvTitle.visibility = titleVisible
        viewBinding.tvTitle.setTextColor(textColor)

    }

    inner class Action {

        fun clickBack() {
            listener?.invoke()
        }
    }

    fun setOnBackClickLister(listener: (() -> Unit)) {
        this.listener = listener
    }

    fun setTitle(title: String?) {
        viewBinding.tvTitle.text = title
    }
}